package com.wateray.ipassbook.ui.action;

import java.awt.HeadlessException;
import java.awt.Toolkit;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.awt.event.ActionEvent;
import java.io.IOException;

import javax.swing.AbstractAction;

import com.wateray.ipassbook.domain.Receipt;
import com.wateray.ipassbook.domain.form.ReceiptForm;
import com.wateray.ipassbook.kernel.service.ReceiptService;
import com.wateray.ipassbook.ui.model.AbstractPassbookTableModel;
import com.wateray.ipassbook.ui.widget.PassbookTable;
import com.wateray.ipassbook.util.CalendarUtils;
import com.wateray.ipassbook.util.ImageManager;
import com.wateray.ipassbook.util.LanguageLoader;

public class ReceiptPasteAction extends AbstractAction {
	
	/**
	 * serialVersionUID
	 */
	private static final long serialVersionUID = 1L;

	public ReceiptPasteAction() {
		super(LanguageLoader.getString("Paste"), ImageManager
				.getImageIconByShortName("paste_edit.gif"));
		putValue(SHORT_DESCRIPTION, LanguageLoader
				.getString("Paste the receipt."));
		putValue(ACTION_COMMAND_KEY, LanguageLoader
				.getString("ReceiptPasteAction"));

		this.setEnabled(false);
	}

	@Override
	public void actionPerformed(ActionEvent e) {
		PassbookTable table = (PassbookTable) this.getValue("PassbookTable");
		if(table == null){
			return;
		}
		
		try {
			Object object = Toolkit.getDefaultToolkit()
					.getSystemClipboard().getContents(null).getTransferData(
							new DataFlavor(ReceiptForm.class, "ReceiptForm"));
			
			if(object == null){
				this.setEnabled(false);
				return;
			}
			ReceiptForm form = (ReceiptForm)object;
			
			form.setReceiptDay(CalendarUtils.getTodayInstance().getBeginDay());
			new ReceiptService().insertReceipt((Receipt) form);

			// invoke receiptTabelModel
			((AbstractPassbookTableModel) table.getModel()).addRow(form);
			
			//disable.
			this.setEnabled(false);

		} catch (HeadlessException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		} catch (UnsupportedFlavorException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
	}

}
